import DialogStore from ".";
import { Button, message } from 'antd';
import { each } from 'lodash';
import { observable, action } from "mobx";
import { WeaForm, WeaTableNew } from 'comsMobx';
import { pathNode, saveNode, addChildNode, operatorList, addOperator, deleteOperator } from "../../apis/path";
//import { pathNode, saveNode, operatorList, addOperator, deleteOperator } from "../../apis/pathTemplate";
import * as API from "../../apis/pathTemplate"
//import { formInfo } from '../../components/path-template/operatorData';
import { TaskViewType } from "../../constants/task";
import { WeaLocaleProvider } from "ecCom";
const getLabel = WeaLocaleProvider.getLabel;
//const { TableStore } = WeaTableNew;
const fieldKeys = {
    uuid: 'uuid',
    id: 'id',
    name: 'name',
    nodeType: 'nodeType',
    operatorType: 'operateType',
    tablename: 'tablename',
    tablekey: 'tablekey',
    showfield: 'showfield',
    isrecursion: 'isrecursion',
    tablesup: 'tablesup',
    relationtype: 'relationtype',
    hrmresource: 'hrmresource',
    hrmdepartment: 'hrmdepartment',
    hrmsubcompany: 'hrmsubcompany',
    rootids: 'rootids',
    supnodefield: 'supnodefield',
    nodefield: 'nodefield',
    hreflink: 'hreflink',
    iscustom: 'iscustom',
    reporttime: 'reporttime',
    reporttimetype: 'reporttimetype',
    reporttype: 'reporttype',
    undotype: 'undotype',
    isreject: 'isreject'
}
export default class NodeModalStore extends DialogStore {
    @observable id;
    @observable parentid;
    @observable form = new WeaForm();
    @observable operatorForm;
    //@observable operatorTableStore = new TableStore();
    @observable itemType = '0';
    @observable order = "0";
    @observable loading = false;

    pathStore;
    @observable parentNodeType;
    @observable parentOperateType;
    //@observable isShowNode = true;

    @observable operatorDataSource = [];
    @observable tableSelectedRowKeys = [];

    constructor(pathStore) {
        super();
        this.pathStore = pathStore;
        this.initOperatorForm();
        this.style = { width: 720 }

        each(fieldKeys, action((value, key) => {
            this.form.add('', { key });
            if (key === 'hreflink') {
                this.form.add('', { key: 'hreflinkType' });
                this.form.add('', { key: 'hreflinkUrl' });
            } else if (key === 'operatorType') {
                this.form.$(key).set('0');
            }

        }));
    }
    @action init = (id, parentid) => {//1.传id,parentid为设置 2.传'',patentid为添加下级
        this.form.resetForm();
        this.loading = true;
        this.id = id;
        this.parentid = parentid;
        this.form.$('reporttime').set('2');
        this.form.$('reporttimetype').set('1');
        this.form.$('undotype').set('0');
        this.form.$('reporttype').set('1');
        if (parentid) {
            this.form.$('nodeType').set('0');
            this.itemType = '0';
            pathNode(parentid).then(node => {
                if (node.nodeType === '0') {
                    this.parentNodeType = '0';
                } else if (node.nodeType === '1') {
                    this.parentNodeType = '1';
                    this.form.$('nodeType').set('1');
                    this.form.$('operatorType').set('0');
                    this.itemType = '6';
                    this.form.$('relationtype').set('1');
                }
                this.parentOperateType = node.operateType;
            })
        }
        if (id) {
            pathNode(id).then(this.initNode);
        }else{
            this.operatorDataSource=[];
        }
        this.initOperatorTable();
        this.buttons = [(<Button type="primary" onClick={this.save}>{getLabel(30986, '保存')}</Button>),
        (<Button type="primary" onClick={this.hide}>{getLabel('31129', '取消')}</Button>)]
    }
    @action initOperatorTable = () => {
        this.initOperatorForm();
        if (this.id) operatorList(this.id).then(this.setOperatorTable);
    }
    @action setOperatorTable = (data) => {
        //this.operatorTableStore.getDatas(data.datas);
        this.operatorDataSource = data.datas;
    }
    @action getHrmresourceDatas() {
        if (this.node) {
            return this.node.hrmresourceObj;
        }
    }
    @action initNode = (node) => {
        this.node = node;
        console.log(node)
        switch (node.nodeType) {
            case '0': this.itemType = '0'; break;
            case '1': this.itemType = '6'; break;
        }
        switch (node.operateType) {
            case '0': this.itemType = '6'; break;
            case '1': this.itemType = '7'; break;
            case '2': this.itemType = '11'; break;
            case '3': this.itemType = '15'; break;
        }
        each(fieldKeys, action((value, key) => {
            if (key === 'hreflink') {
                const [hreflinkType = TaskViewType, hreflinkUrl = '', hreflink = ''] = node.hreflinkObj || [];
                this.form.$('hreflink').set(hreflink);
                this.form.$('hreflinkUrl').set(hreflinkUrl);
                this.form.$('hreflinkType').set(hreflinkType);
            } else if (key === 'hrmresource') {
                const datas = node.hrmresource && node.hrmresource.valueObj || [];
                this.form.$('hrmresource').onChange(datas.map(d => d.id).join(','), '', datas);
            } else if (key === 'hrmdepartment') {
                const datas = node.hrmdepartment && node.hrmdepartment.valueObj || [];
                this.form.$('hrmdepartment').onChange(datas.map(d => d.id).join(','), '', datas);
            } else if (key === 'hrmsubcompany') {
                const datas = node.hrmsubcompany && node.hrmsubcompany.valueObj || [];
                this.form.$('hrmsubcompany').onChange(datas.map(d => d.id).join(','), '', datas);
            } else if (key === 'rootids') {
                const datas = node.operateType === '3' ? node.rootids : ''
                this.form.$('rootids').onChange(datas);
            } else if (key === 'undotype') {
                this.form.$('undotype').set(`${node.undotype}`);
            } else {
                this.form.$(key).set(node[value]);
            }
        }));
        this.initOperatorForm();
        this.loading = false;
    }

    $ = (name) => {
        return this.form.$(name);
    }
    @action initOperatorForm = () => {
        this.operatorForm = new WeaForm();
        //const typeDetail = formInfo[this.itemType] || {};
        //const items = typeDetail.items || [];
        //const conditions = [{ defaultshow: true, items }];
        //this.operatorForm.initFormFields(conditions);
    }
    @action changeNodeType = (value) => {
        this.form.$('nodeType').set(value);
        if (value === '0') {
            this.itemType = '0';
        } else if (value === '1') {
            this.form.$('operatorType').set('0');
            if (this.parentNodeType === '0') {
                this.form.$('relationtype').set('0');
            } else if (this.parentNodeType === '1') {
                this.form.$('relationtype').set('1');
            }
            this.itemType = '6';
        }
        this.initOperatorTable();
    }
    @action changeOperatorType = (value) => {
        this.form.$('operatorType').set(value);
        switch (value) {
            case '0': this.itemType = '6'; break
            case '1': this.itemType = '7'; break
            case '2': this.itemType = '11'; break
            case '3': this.itemType = '15'; break
        }
        this.initOperatorForm();
    }

    @action changeItemType = (value) => {
        this.itemType = value;
        this.initOperatorForm();
    }
    @action setOrder = (order) => {
        this.order = order;
    }
    @action addOperator = () => {
        const rootids = this.getParams().rootids ? this.getParams().rootids : '';
        if (this.checkOperatorParams()) {
            //addOperator({ ...this.operatorForm.getFormParams(), nodeid: this.id, shareType: this.itemType,rootids: rootids}).then(this.initOperatorTable);
            //console.log("添加操作者的参数", { ...this.operatorForm.getFormParams(), nodeid: this.id, shareType: this.itemType, rootids: rootids })
            const name = this.operatorForm.getFormDatas().field && this.operatorForm.getFormDatas().field.valueSpan;
            const type = this.getOperatorType();
            const relationtype = this.form.$('relationtype').value
            if(relationtype==='0'&&(this.itemType==='6'||this.itemType==='7'||this.itemType==='8'||this.itemType==='9'||this.itemType==='11'||this.itemType==='12'||this.itemType==='13')){
                let valueSpan = [];
                switch(this.itemType){
                    case '6':valueSpan=this.form.$('hrmresource').valueObj;break;
                    case '7':valueSpan=this.form.$('hrmdepartment').valueObj;break;
                    case '11':valueSpan=this.form.$('hrmsubcompany').valueObj;break;
                }
                if(valueSpan&&valueSpan.length>0){
                    valueSpan.map(v=>{
                        this.operatorDataSource = [...this.operatorDataSource, {
                            key: 'n'+this.operatorDataSource.length,
                            name: v.name,
                            type: type,
                            levelString: this.getLevelString(),
                            ...this.operatorForm.getFormParams(),
                            shareType: this.itemType,
                            rootids: v.id
                        }];
                    })
                }else{
                    message.error("未设置指定对象");
                }
            }else{
                this.operatorDataSource = [...this.operatorDataSource, {
                    key: 'n'+this.operatorDataSource.length,
                    name: name,
                    type: type,
                    levelString: this.getLevelString(),
                    ...this.operatorForm.getFormParams(),
                    shareType: this.itemType,
                    rootids: rootids
                }];
            }
            this.initOperatorForm();
        }
    }
    @action save = () => {//1.传id,parentid为保存 2.传'',patentid为添加下级
        this.loading = true;
        const values = this.form.values();
        if (this.id) {
            const diffs = this.getParams();
            if (this.checkParams(values)) {
                saveNode({ id: this.id, ...diffs,operators:JSON.stringify(this.operatorDataSource) }).then((result) => { this.pathStore.setNode(result); });
                message.success("保存成功！");
                this.hide();
            }
        } else if (this.parentid) {
            each(values, (value, key) => {
                if (key === 'hrmsubcompany' || key === 'hrmdepartment' || key === 'hrmresource' || key === 'rootids') {
                    const { operatorType } = values;
                    const selectedKey = { '0': 'hrmresource', '1': 'hrmdepartment', '2': 'hrmsubcompany', '3': 'rootids' }[operatorType];
                    if (key === selectedKey) {
                        values.rootids = values[key]
                    }
                }
            })
            if (this.checkParams(values)) {
                addChildNode({ parentid: this.parentid, ...values,operators:JSON.stringify(this.operatorDataSource) }).then((result) => {
                    this.pathStore.setNode(result);
                    message.success("添加成功！");
                    this.hide();
                });
            }
        }
    }

    @action deleteOperator = () => {
        this.tableSelectedRowKeys.map(key => {
            this.operatorDataSource.splice(this.operatorDataSource.findIndex(item => item.key === key), 1)
            this.operatorDataSource=[...this.operatorDataSource];
        })
    }


    getParams = () => {
        const values = this.form.values();
        const diffs = {};
        each(fieldKeys, (value, key) => {
            if (values[key] !== 'value' && this.node && values[key] !== this.node[value]) {
                if (key === 'hrmsubcompany' || key === 'hrmdepartment' || key === 'hrmresource' || key === 'rootids') {
                    const { operatorType } = values;
                    const selectedKey = { '0': 'hrmresource', '1': 'hrmdepartment', '2': 'hrmsubcompany', '3': 'rootids' }[operatorType];
                    if (key === selectedKey) {
                        diffs.rootids = values[key]
                    }
                } else {
                    diffs[key] = values[key]
                }
            }
        });
        if (values['name'] == 'value') diffs['name'] = values['name']//上面过滤掉了值为value的情况,但节点名称name应可以取值value
        return diffs;
    }


    checkParams = (values) => {
        console.log(values)
        let flag = false;
        if (typeof values.name === 'string' && values.name.trim() === '') {
            message.error("未填写节点名称")
        } else if (values.nodeType === '1') {
            if (values.operatorType === '3') {
                if (values.tablename === '') {
                    message.error("未设置自定义对象表名")
                } else if (values.tablekey === '') {
                    message.error("未设置自定义对象主键")
                } else if (values.showfield === '') {
                    message.error("未设置自定义对象显示名称")
                } else if (values.isrecursion==='1'&&values.tablesup === '') {
                    message.error("未设置上级字段")
                } else if (values.relationtype === '0' && values.rootids === '') {
                    message.error("未设置指定对象")
                } else if (values.relationtype === '1') {
                    if (values.supnodefield === '') {
                        message.error("未设置上级节点字段")
                    } else if (values.nodefield === '') {
                        message.error("未设置本级节点字段")
                    } else {
                        flag = true;
                    }
                } else {
                    flag = true;
                }
            } else if (values.relationtype === '0' && values.rootids === '' && values.hrmresource==='' && values.hrmdepartment==='' && values.hrmsubcompany==='') {
                message.error("未设置指定对象")
            } else {
                flag = true;
            }
        } else {
            flag = true;
        }
        return flag;
    }

    checkOperatorParams = () => {
        let flag = false;
        const field = this.operatorForm.getFormParams().field;
        const shareType = this.itemType;
        const relationtype = this.getParams().relationtype
        //const rootids = this.getParams().rootids ? this.getParams().rootids : '';
        const joblevel = this.operatorForm.getFormParams().joblevel
        const jobid_dept = this.operatorForm.getFormParams().jobid_dept ? this.operatorForm.getFormParams().jobid_dept : '';
        const jobid_subcom = this.operatorForm.getFormParams().jobid_subcom ? this.operatorForm.getFormParams().jobid_dept : '';
        if (field !== '' || shareType === '5' || shareType === '6' || shareType === '7' || shareType === '11'|| shareType === '15' ) {
             if (shareType === '4') {
                if (joblevel === '0' && jobid_dept === '') {
                    message.error("未指定部门");
                } else if (joblevel === '1' && jobid_subcom === '') {
                    message.error("未指定分部");
                } else {
                    flag = true;
                }
            } else {
                flag = true;
            }
        } else {
            message.error("未指定对象");
        }
        return flag;
    }

    getOperatorType = () => {
        let type = '';
        switch (this.itemType) {
            case '0': type = getLabel('502663', '指定人'); break;
            case '1': type = getLabel('502664', '指定部门'); break;
            case '2': type = getLabel('502665', '指定分部'); break;
            case '3': type = getLabel('502666', '指定角色'); break;
            case '4': type = getLabel('502667', '指定岗位'); break;
            case '5': type = getLabel('502668', '所有人'); break;
            case '6': type = getLabel('502669', '本人'); break;
            case '7': type = getLabel('502670', '本部门'); break;
            case '8': type = getLabel('502671', '本部门角色'); break;
            case '9': type = getLabel('502672', '本部门岗位'); break;
            case '11': type = getLabel('30792', '本分部'); break;
            case '12': type = getLabel('502674', '本分部角色'); break;
            case '13': type = getLabel('502675', '本分部岗位'); break;
            case '15': type = getLabel('502677', '人力资源相关字段'); break;
        }
        return type;
    }
    getLevelString = () => {
        let levelString = levelString = this.operatorForm.getFormDatas().level && this.operatorForm.getFormDatas().level.value[0]+'-'+this.operatorForm.getFormDatas().level.value[1];
        switch (this.itemType) {
            case '3':
                const rolelevel = this.operatorForm.getFormParams().rolelevel;
                levelString = rolelevel === '0' ? getLabel(502298, "部门") : rolelevel === '1' ? getLabel(502299, "分部") : getLabel('140', '总部');
                break;
            case '4': 
                const joblevel = this.operatorForm.getFormParams().joblevel;
                const joblevelSpan = this.operatorForm.getFormDatas().joblevel.value.length>1?this.operatorForm.getFormDatas().joblevel.value[1][1]:'';
                levelString = joblevel ==='0' ? getLabel('502665', '指定分部')+'('+joblevelSpan+')' : joblevel === '1' ? getLabel('502664', '指定部门')+'('+joblevelSpan+')' : getLabel('140', '总部');
                break;
        }
        return levelString;
    }
    

}